package com.ruoyi.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.estate.Resident;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysRegisterService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.estate.IResidentService;

/**
 * 注册校验方法
 */
@Service
public class SysRegisterServiceImpl implements ISysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IResidentService residentService;

    /**
     * 注册
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult register(RegisterBody registerBody)
    {
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        // 验证码开关 - 注册不需要验证码
        // boolean captchaEnabled = configService.selectCaptchaEnabled();
        // if (captchaEnabled)
        // {
        //     validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        // }

        if (StringUtils.isEmpty(username))
        {
            return AjaxResult.error("用户名不能为空");
        }
        else if (StringUtils.isEmpty(password))
        {
            return AjaxResult.error("用户密码不能为空");
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            return AjaxResult.error("账户长度必须在2到20个字符之间");
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            return AjaxResult.error("密码长度必须在5到20个字符之间");
        }
        else if (!userService.checkUserNameUnique(sysUser))
        {
            return AjaxResult.error("保存用户'" + username + "'失败，注册账号已存在");
        }

        sysUser.setNickName(registerBody.getNickName());
        sysUser.setPhonenumber(registerBody.getPhonenumber());
        sysUser.setEmail(registerBody.getEmail());
        sysUser.setSex(registerBody.getSex());
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        boolean regFlag = userService.registerUser(sysUser);
        if (!regFlag)
        {
            return AjaxResult.error("注册失败,请联系系统管理人员");
        }

        // 获取新创建的用户ID
        SysUser newUser = userService.selectUserByUserName(username);
        if (newUser == null)
        {
            return AjaxResult.error("用户创建成功但无法获取用户信息");
        }

        // 创建住户信息
        Resident resident = new Resident();
        resident.setHouseId(registerBody.getHouseId());
        resident.setResidentName(registerBody.getNickName());
        resident.setGender(registerBody.getSex());
        resident.setIdCard(registerBody.getIdCard());
        resident.setPhone(registerBody.getPhonenumber());
        resident.setEmail(registerBody.getEmail());
        resident.setResidentType(registerBody.getResidentType());
        resident.setCheckInDate(registerBody.getCheckInDate());
        resident.setStatus("0"); // 正常状态
        resident.setDelFlag("0"); // 未删除
        
        // 设置关联的用户ID，将用户表和住户表关联起来
        resident.setUserId(newUser.getUserId());
        
        residentService.insertResident(resident);

        return AjaxResult.success("注册成功");
    }

    /**
     * 校验用户名是否唯一
     */
    @Override
    public AjaxResult checkUserNameUnique(String userName)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        return userService.checkUserNameUnique(sysUser) ? AjaxResult.success() : AjaxResult.error("用户名已存在");
    }

    /**
     * 校验验证码
     */
    private void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = "captcha_codes:" + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }
} 